package org.enhance.idempotent.core.config;

import org.enhance.common.annotation.ConditionalOnProperties;
import org.enhance.common.helper.ApplicationContextHelper;
import org.enhance.idempotent.core.aspect.IdempotentAspect;
import org.enhance.idempotent.core.config.properties.IdempotentCoreProperties;
import org.enhance.idempotent.core.handler.DefaultIdempotentExceptionEventHandler;
import org.enhance.idempotent.core.handler.IdempotentExceptionEventHandler;
import org.enhance.idempotent.core.helper.IdempotentHelper;
import org.enhance.idempotent.core.registry.IdempotentRepositoryRegistrySupport;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.lang.NonNull;

/**
 * <p>
 * 幂等核心自动配置
 * </p>
 *
 * @author wenpan 2023/01/04 21:56
 */
@Configuration
@ConditionalOnProperties(prefix = "enhance.idempotent", properties = {"enable"}, values = {"true"})
@EnableConfigurationProperties({IdempotentCoreProperties.class})
public class IdempotentCoreAutoConfiguration {

    @Bean("applicationContextHelper")
    public ApplicationContextHelper applicationContextHelper() {
        return new ApplicationContextHelper();
    }

    @Bean
    @DependsOn({"idempotentHelper"})
    @ConditionalOnMissingBean({IdempotentAspect.class})
    public IdempotentAspect idempotentAspect() {
        return new IdempotentAspect();
    }

    @Bean
    @ConditionalOnMissingBean
    public IdempotentExceptionEventHandler defaultIdempotentExceptionEventHandler() {
        return new DefaultIdempotentExceptionEventHandler();
    }

    @Bean
    public IdempotentRepositoryRegistrySupport idempotentRepositoryRegistrySupport(IdempotentCoreProperties properties) {
        return new IdempotentRepositoryRegistrySupport(properties);
    }

    @Bean("idempotentHelper")
    @ConditionalOnMissingBean
    public IdempotentHelper idempotentHelper(@NonNull IdempotentExceptionEventHandler exceptionEventHandler,
                                             @NonNull IdempotentCoreProperties idempotentCoreProperties) {
        return new IdempotentHelper(exceptionEventHandler, idempotentCoreProperties);
    }

}
